#! /usr/bin/env python

VERSION='0.1'
APPNAME='docs'

srcdir = '.'
blddir = 'build'

import waflib.Utils
import sys, os, re, fnmatch
import waflib.Options
import waf_dynamo
import TestContext

test_context = None

def init(ctx):
    global test_context
    if 'build' in waflib.Options.commands:
        test_context = TestContext.create_test_context()

def configure(conf):
    conf.recurse('src')
    pass

def clean(conf):
    # Clean up src
    files = os.listdir('src')
    for filename in fnmatch.filter(files, '*.apidoc_'):
        os.remove(os.path.join('src', filename))

def build(bld):
    global test_context
    # Clean up src
    files = os.listdir('src')
    for filename in fnmatch.filter(files, '*.apidoc_'):
        os.remove(os.path.join('src', filename))

    # Find all the built .apidoc files in the engine tree
    apidoc_files = []
    for root, dirs, files in os.walk('..'):
        for filename in fnmatch.filter(files, '*.apidoc'):
            apidoc_files.append(os.path.join(root, filename))
    # Concat per namespace into 'src'
    namespace_files = {}
    for apidoc_file in apidoc_files:
        namespace, _ = os.path.splitext(os.path.basename(apidoc_file))
        if namespace not in namespace_files:
            namespace_files[namespace] = []
        namespace_files[namespace].append(apidoc_file)
    for ns, files in namespace_files.items():
        comments = '\n'.join([waflib.Utils.readf(f, encoding='utf-8') for f in files])
        with open('src/%s.apidoc_' % ns, 'w') as out_f:
            out_f.write(comments)
    bld.recurse('src')
    TestContext.initialize_test_context(test_context, bld)

def options(opt):
    opt.recurse('src')
    opt.load('waf_dynamo')
    opt.add_option('--skip-tests', action='store_true', default=False, dest='skip_tests', help='skip unit tests')

def shutdown(self):
    if not TestContext.is_valid(test_context):
        return
    if not getattr(waflib.Options.options, 'skip_tests', False):
        python_path = os.environ.get('PYTHONPATH', '')
        os.environ['PYTHONPATH'] = 'src' + os.pathsep + 'build/default/src' + os.pathsep + python_path
        ret = os.system('python %s' % 'src/test/test_script_doc.py')
        if ret != 0:
            sys.exit(1)
